#include <zemb/Socket.h>
#include <zemb/Tracer.h>
#include <zemb/FileUtil.h>
#include <zemb/StrUtil.h>
#include <zemb/ArgUtil.h>

using namespace zemb;

int main(int argc, char* argv[])
{
	ArgOption  option;
	uint16 port=5555;
	std::string ip = "127.0.0.1";
	std::string localip = "127.0.0.1";
	Tracer::getInstance().setLevel(TRACE_LEVEL_DBG);
	Tracer::getInstance().addSink(std::make_shared<STDSink>()).start();

	if(!option.parseArgs(argc,argv))	/* 解析参数 */
	{
		return RC_ERROR;
	}
	if(option.hasOption("h")>=0)
	{
		FilePath filePath(argv[0]);
		TRACE_YELLOW("tcp client help:");
		TRACE_YELLOW("%s [-h] [-l localip] [-p port] [-i ip]",CSTR(filePath.baseName()));
		TRACE_YELLOW("        -h  help");
		TRACE_YELLOW("        -l  local ip");
		TRACE_YELLOW("        -p  server port");
		TRACE_YELLOW("        -i  server ip");
		return RC_OK;
	}

	if(option.hasOption("l")>0)
	{
		localip = option.getValue("l")[0];
	}

	if(option.hasOption("i")>0)
	{
		ip = option.getValue("i")[0];;
	}
		
	if(option.hasOption("p")>0)
	{
		port = (uint16)std::stoi(option.getValue("p")[0]);
	}
	else
	{
		TRACE_ERR("tcp client need server port: [-p port]!");
		return RC_ERROR;
	}
	
     /* 客户端建立连接 */
	TcpSocket client;
	if(!client.open(localip,port-1))
	{
		TRACE_ERR("cannot open local socket!");
		return RC_ERROR;
	}
	if (!client.setConnection(ip,port))
	{
		TRACE_ERR("cannot connect server: %s:%d",CSTR(ip),port);
		return RC_ERROR;
	}
	TRACE_INFO("connect server ok: %s:%d",CSTR(ip),port);
	while(1)
	{
		std::string msg="hello, i am client!";
		if(client.sendData(CSTR(msg),msg.size() ,1000)<=0)
		{
			TRACE_ERR("send msg to server error!");
		}
		else
		{
			TRACE_INFO("send msg to server ok!");
		}
		Thread::msleep(2000);
	}
    return 0;
}
